package utils;

import java.io.File;
import java.io.FileInputStream;
import play.Logger;

import com.qiniu.api.auth.digest.Mac;
import com.qiniu.api.config.Config;
import com.qiniu.api.io.IoApi;
import com.qiniu.api.io.PutExtra;
import com.qiniu.api.io.PutRet;
import com.qiniu.api.rs.PutPolicy;

public class QiNiuUtil {
	

	public static String uploadFile(File file) {
		
		String key = StringUtils.getMengCode();
		try {
			Config.ACCESS_KEY = AppConfig.QN_AK;
			Config.SECRET_KEY = AppConfig.QN_SK;
			Mac mac = new Mac(Config.ACCESS_KEY, Config.SECRET_KEY);
			// 请确保该bucket已经存在
			String bucketName = AppConfig.QN_bucket;
			PutPolicy putPolicy = new PutPolicy(bucketName);
			String uptoken = putPolicy.token(mac);
			PutExtra extra = new PutExtra();
			FileInputStream fis = new FileInputStream(file);
			PutRet ret = IoApi.Put(uptoken, key, fis, extra);
			if(ret.ok()){
				return AppConfig.QN_domain + key;
			}
		} catch (Exception e) {
			Logger.error("qiniu upload file failure, [key]="+ key);
		}
		return "upload failure";
	}
	
}
